<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @author  Nguyen Xuan Hung
 * @email   hungnguyen@vietnambiz.com
 * @date    19.11.2010
 */
 
class Auth_model extends CI_Model {
    
    function __construct()
    {
        parent::__construct();
    }
    
    function login($user = '', $pass = '')
    {
        $user = $this->db->where('username', $user)
                         ->where('password', $pass)
                         ->where('status', 'active')
                         ->get('users')->row_array();

        if($user) {
            $_SESSION['_user'] = $user;
            return true;
        }
        else return false;
    }
    
    function logout()
    {
        //session_destroy();
        unset($_SESSION['_user']);
        return true;
    }
    
    // Note : method '*' is all method of controller
    function check_permission($controller = '', $method = '')
    {
        $allow   = false;
        $user    = $_SESSION['_user'];
        if($user['group_id'] == 1) $allow = true;
        $all_per = $this->db->from('modules as m')->join('permissions as p','m.id=p.module_id')->where('group_id', $user['group_id'])
                            ->where_in('m.name', array('*', $controller))
                            ->where_in('method', array('*', $method))
                            ->get()
                            ->result_array();

        if(count($all_per) < 1) {
            return false;
        }
        
        //print_r($all_per);
        
        foreach($all_per as $per) {
            if($per['status'] == 'active') $allow = true;
            else {$allow = false;break;}
        }

        return $allow;
    }
    
	function check_login()
    {
    	$user	=	$_SESSION['_user'];
    	if($user){
	    	$row	=	$this->db->where(array('username' => $user['username'], 'password' => $user['password'], 'status' => 'active'))->get('users')->row();
	    	if($row)return TRUE;
    	}
    	return FALSE;
    	
    }
    
	function check_login_admin()
    {
    	$user	=	$_SESSION['_user'];
    	if($user){
	    	$row	=	$this->db->where(array('username' => $user['username'], 'password' => $user['password'], 'status' => 'active', 'group_id' => '1'))->get('users')->row();
	    	
	    	if($row)return TRUE;
    	}
    	return FALSE;
    	
    }
}
